import numpy as np
import pandas as pd
import os
import time
import glob
import re
import warnings
from program.pack.append_df_to_excel import append_df_to_excel
from pandas import to_datetime
from functools import reduce
import pandas as pd

pd.set_option('display.max_rows', 999)
pd.set_option('precision', 10)
pd.set_option('expand_frame_repr', True)
warnings.filterwarnings("ignore")

# 列显示不全，进行设置
pd.set_option('display.max_columns', 500)
pd.set_option('display.unicode.ambiguous_as_wide', True)
pd.set_option('display.unicode.east_asian_width', True)
pd.set_option('display.width', 180)  # 设置打印宽度(**重要**)


# --------------txt --------------
def func_txt(data_txt):
    data_txt['角度'] = data_txt['文件'].astype(str).str.split(' ').str[0]
    data_txt['信号强度dB'] = data_txt['文件'].astype(str).str.split(' ').str[1]
    # print(data_txt.dtypes)
    data_txt['角度'] = data_txt['角度'].astype(float)
    data_txt['信号强度dB'] = data_txt['信号强度dB'].astype(float)
    data_txt = data_txt.round(10)

    return data_txt


def func_txt_x(path_inputs=[r'Z:\minhang_tai40_1\train\20210513xinjiang_train\0521']):
    k = 0
    for path_input in path_inputs:  # 支持多文件夹遍历
        # os.walk(file_path) 深度遍历file_path下的所有子文件夹及文件
        for root_dir, sub_dir, files in os.walk(path_input):
            for file in files:
                dfs = pd.DataFrame()
                # 进行条件筛选   以非~$'开头(解决读取文档已打开问题)；选择以file_name_0结尾的文档
                if (file.startswith('~$') is False) and file.endswith('msi'):
                    # 构造文件的绝对路径 = 文件夹路径 + 文件
                    file_name = os.path.join(root_dir, file)
                    # file_name = file_name.replace('msi', 'txt', regex=True)
                    # file_name
                    file = open(file_name, "r")
                    list_txt = file.read().splitlines()[11:]  # 每一行数据写入到list中
                    data_t = pd.DataFrame({'文件': list_txt})
                    data_t = func_txt(data_t)
                    data_t['msi文件地址'] = root_dir
                    data_t['信号最大值'] = data_t['信号强度dB'].min()
                    data_t.sort_values(by=['信号强度dB'], ascending=True, inplace=True)

                    # import seaborn as sns
                    import matplotlib.pyplot as plt
                    import warnings
                    # 忽略警告
                    warnings.filterwarnings("ignore")
                    # 支持中文
                    plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
                    plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

                    list_names = list(data_t['角度'])
                    list_nums = list(data_t['信号强度dB'])

                    list_x = [float('{:.2f}'.format(100 * i)) for i in list_names]
                    list_y = [float('{:.2f}'.format(100 * i)) for i in list_nums]
                    plt.plot(list_x, list_y, 'rs-', markersize=10)

                    # 取得纵坐标取值范围，方便后续查看
                    # max_0 = max(max(list_names), max(list_106))
                    # min_0 = min(min(list_100z), min(list_106))

                    k += 1
                    print(root_dir, '第', k, '个txt文件读取成功')
                    path_out = file_name.split('.msi')[0] + '.xlsx'
                    path_out_jpg = file_name.split('.msi')[0] + '.jpg'
                    plt.savefig(path_out_jpg)
                    plt.close()
                    append_df_to_excel(path_out, data_t, sheet_name='data', startcol=0, startrow=0, index=False)
    return dfs


# ---------txt程序已结束---------

if __name__ == "__main__":
    # 记录时间
    start = time.time()

    # 数据源地址
    paths = r'C:\Users\wangshuan\Desktop\潘'
    path_inputs = [paths]
    # 数据清洗输出位置
    # path_out = r'..\\data\潘_data.xlsx'

    # txt文件读取写入, [key_d，图片，坐标，正，反，max], [key_o，图片，坐标，正，反，max]
    data_txt = func_txt_x(path_inputs=path_inputs)

    # append_df_to_excel(path_out, data_txt, sheet_name='data', startcol=0, startrow=0, index=False)
    # 记录时间
    end = time.time()
    print("代码运行耗时{:.2f}秒".format(end - start))
